package org.daochong.web.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpMethodFilter implements Filter {
	private List<String> methods = new ArrayList<String>();

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		String method = request.getMethod().toUpperCase();
		if (!this.methods.contains(method))
			response.setStatus(405);
		else
			filterChain.doFilter(req, resp);
	}

	public void init(FilterConfig config) throws ServletException {
		if (config.getInitParameter("methods") != null) {
			for (String method : config.getInitParameter("methods").split(","))
				this.methods.add(method.toUpperCase());
		} else {
			this.methods.add("OPTIONS");
			this.methods.add("HEAD");
			this.methods.add("TRACE");
		}
	}
}